<template>
  <view class="ranking-container">
    <view class="ranking-card">
      <!-- 顶部按钮 + 时间范围选择（同一行等高） -->
      <view class="tab-row">
        <button 
          :class="['tab-btn', rankingType === 'class' ? 'active' : '']" 
          @click="switchRankingType('class')"
        >
          班级违纪排名
        </button>
        <button 
          :class="['tab-btn', rankingType === 'teacher' ? 'active' : '']" 
          @click="switchRankingType('teacher')"
        >
          老师排名
        </button>
        <picker class="picker-flex" mode="selector" :range="['周排名','月排名','学期排名']" @change="onRangeChange" :value="rangeIndex">
          <view class="tab-btn picker-btn">{{ rangeLabel }}</view>
        </picker>
      </view>
      <view class="result" v-if="loaded">
        <!-- 班级违纪排名 -->
        <view v-if="rankingType === 'class'">
          <view class="top-list" v-if="topList.length > 0">
            <view style="font-weight: bold; padding: 8px 0; color: #333">
              我的班级排名（共 {{ topList.length }} 个班级）
            </view>
            
            <view 
              class="top-item" 
              v-for="(item, idx) in topList" 
              :key="idx" 
              @click="goToClassDetail(item.className)"
            >
              <!-- 显示全校排名(如果有rank),否则显示序号 -->
              <text :style="{ color: (item.rank || idx+1) <= 3 ? '#e74c3c' : '#333', fontWeight: (item.rank || idx+1) <= 3 ? 'bold' : 'normal' }">
                <text v-if="item.rank">第{{ item.rank }}名</text>
                <text v-else>{{ idx+1 }}.</text>
                {{ item.displayName }} - {{ item.count }} 次
              </text>
            </view>
          </view>
          <view v-else class="no-data">
            <text>该时间范围内暂无违纪记录</text>
          </view>
        </view>
        
        <!-- 老师排名 -->
        <view v-else-if="rankingType === 'teacher'">
          <view v-if="teacherList.length > 0">
            <!-- 巡班老师：显示全校老师排名列表 -->
            <view v-if="isPatrolTeacher">
              <view style="font-weight: bold; padding: 8px 0; color: #333; border-bottom: 1px solid #f0f0f0; margin-bottom: 10px">
                全校老师排名 (共 {{ teacherList.length }} 位老师)
              </view>
              
              <view class="top-list">
                <view 
                  class="top-item" 
                  v-for="(teacher, idx) in teacherList" 
                  :key="idx"
                >
                  <text :style="{ 
                    color: teacher.rank <= 3 ? '#e74c3c' : '#333', 
                    fontWeight: teacher.rank <= 3 ? 'bold' : 'normal',
                    backgroundColor: teacher.isCurrentUser ? '#fff3cd' : 'transparent',
                    padding: teacher.isCurrentUser ? '4px 8px' : '0',
                    borderRadius: teacher.isCurrentUser ? '4px' : '0'
                  }">
                    第{{ teacher.rank }}名 {{ teacher.teacherName }} - {{ teacher.count }} 次
                    <text v-if="teacher.isCurrentUser" style="color: #ff9800; font-size: 12px"> (我)</text>
                  </text>
                </view>
              </view>
            </view>
            
            <!-- 普通老师：只显示自己的违纪记录 -->
            <view v-else>
              <!-- 显示我的排名信息 -->
              <view v-if="myTeacherRank" 
                class="rank-info" 
                :style="{ background: myTeacherRank <= 3 ? '#fff3cd' : '#e3f2fd' }"
              >
                <text :style="{ color: myTeacherRank <= 3 ? '#e74c3c' : '#333', fontWeight: 'bold', fontSize: '16px' }">
                  我的排名: 第{{ myTeacherRank }}名 / 共{{ totalTeachers }}位老师
                </text>
              </view>
              
              <view style="font-weight: bold; padding: 8px 0; color: #333; border-bottom: 1px solid #f0f0f0; margin-bottom: 10px; margin-top: 12px">
                我的违纪统计 (共 {{ totalTeacherClasses }} 个班级)
              </view>
              
              <view style="padding: 12px; background: #f9f9f9; border-radius: 8px; margin-bottom: 12px">
                <text style="font-size: 14px; color: #666">
                  {{ teacherSummary }}
                </text>
              </view>
              
              <view class="top-list" v-if="teacherClassList.length > 0">
                <view 
                  class="top-item" 
                  v-for="(item, idx) in teacherClassList" 
                  :key="idx"
                  @click="goToClassDetail(item.originalClassName)"
                >
                  <text :style="{ color: '#333' }">
                    {{ item.displayName }} - {{ item.count }} 次
                  </text>
                </view>
              </view>
            </view>
          </view>
          <view v-else class="no-data">
            <text>{{ teacherEmptyMessage }}</text>
          </view>
        </view>
      </view>
      <view v-if="loading" class="loading">正在查询中...</view>
      <view v-if="!loaded && !loading" class="no-data" style="margin-top: 20px">
        <text>正在加载数据...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import config from '@/config'

export default {
  computed: {
    ...mapGetters(['roles']),
    // 判断是否为巡班老师
    isPatrolTeacher() {
      if (!this.roles || this.roles.length === 0) return false
      return this.roles.some(role => 
        role === 'patrol_teacher' || 
        role.includes('patrol') || 
        role.includes('巡班')
      )
    }
  },
  data() {
    return {
      rangeIndex: 0,
      rangeLabel: '周排名',
      // removed free-text class search; use rankingType to switch
      rankingType: 'class', // 'class' | 'teacher'
      className: '',
      loading: false,
      loaded: false,
      topList: [],
      teacherList: [],
      teacherClassList: [],  // 老师的班级列表
      teacherSummary: '',     // 老师统计摘要
      totalTeacherClasses: 0, // 老师班级总数
      teacherEmptyMessage: '该时间范围内暂无违纪记录',
      myTeacherRank: null,    // 我的排名
      totalTeachers: 0,       // 总老师数
      targetRank: null,
      totalRecords: 0,
      myAccessibleClasses: []  // 当前用户有权限查看的班级列表
    }
  },
  onLoad() {
    // 页面加载时先获取用户有权限查看的班级列表
    this.loadMyAccessibleClasses()
    // 然后自动查询周排名数据
    this.queryRank()
  },
  methods: {
    // 加载当前用户有权限查看的班级列表
    async loadMyAccessibleClasses() {
      try {
        const token = getToken()
        // 调用普通的patrol/page接口(带权限过滤),获取自己能看到的所有班级
        const response = await uni.request({
          url: config.baseUrl + '/admin-api/ao/patrol/page',
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + token,
            'tenant-id': '1',
            'Content-Type': 'application/json'
          },
          data: {
            pageNo: 1,
            pageSize: 1000  // 获取足够多的数据以提取所有班级
          }
        })
        
        const [err, res] = response
        if (!err && res.data && res.data.code === 0) {
          const list = res.data.data?.list || []
          // 提取所有班级名称,去重
          const classSet = new Set()
          list.forEach(item => {
            if (item.className) {
              classSet.add(item.className)
            }
          })
          this.myAccessibleClasses = Array.from(classSet)
        }
      } catch (err) {
        console.error('获取权限班级列表失败:', err)
      }
    },
    
    onRangeChange(e) {
      this.rangeIndex = e.detail.value
      const labels = ['周排名','月排名','学期排名']
      this.rangeLabel = labels[this.rangeIndex]
      // 切换时间范围时自动查询
      this.queryRank()
    },
    switchRankingType(type) {
      if (this.rankingType === type) return
      this.rankingType = type
      // 清空数据，重新查询
      this.topList = []
      this.teacherList = []
      this.queryRank()
    },
    async queryRank() {
      // 拉取后端违纪数据并统计
      // 步骤1: 先获取全校数据(用于计算真实排名)
      // 步骤2: 再获取自己有权限的数据(用于显示)
      this.loading = true
      this.loaded = false
      this.topList = []
      this.targetRank = null
      this.totalRecords = 0
      this.teacherList = []
      try {
        const token = getToken()
        // 计算时间范围
        const today = new Date()
        let classDate = []
        if (this.rangeIndex === 0) {
          // 本周: 周一 - 周日
          const day = today.getDay() || 7
          const monday = new Date(today)
          monday.setDate(today.getDate() - (day-1))
          const sunday = new Date(monday)
          sunday.setDate(monday.getDate() + 6)
          classDate = [this.formatDate(monday) + ' 00:00:00', this.formatDate(sunday) + ' 23:59:59']
        } else if (this.rangeIndex === 1) {
          // 本月
          const start = new Date(today.getFullYear(), today.getMonth(), 1)
          const end = new Date(today.getFullYear(), today.getMonth()+1, 0)
          classDate = [this.formatDate(start) + ' 00:00:00', this.formatDate(end) + ' 23:59:59']
        } else {
          // 学期 (简单实现: 从今年1月1日到今天)
          const start = new Date(today.getFullYear(), 0, 1)
          classDate = [this.formatDate(start) + ' 00:00:00', this.formatDate(today) + ' 23:59:59']
        }

        // 步骤1: 先用排名专用接口获取全校数据(计算真实排名)
        let allSchoolList = []
        let allSchoolRankMap = new Map()  // 保存全校排名: 班级名 -> 排名
        
        try {
          let pageNo = 1
          const pageSize = 100
          let hasMore = true
          
          while (hasMore) {
            const params = { pageNo, pageSize, classDate }
            const response = await uni.request({
              url: config.baseUrl + '/admin-api/ao/patrol/page-for-ranking',
              method: 'GET',
              header: {
                'Authorization': 'Bearer ' + token,
                'tenant-id': '1',
                'Content-Type': 'application/json'
              },
              data: params
            })
            const [err, res] = response
            if (!err && res.data && res.data.code === 0) {
              const list = res.data.data?.list || []
              allSchoolList = allSchoolList.concat(list)
              const total = res.data.data?.total || 0
              if (allSchoolList.length >= total) {
                hasMore = false
              } else {
                pageNo++
              }
            } else {
              hasMore = false
            }
          }
          
          // 统计全校排名
          const schoolMap = new Map()
          allSchoolList.forEach(item => {
            const cls = item.className || '未知班级'
            schoolMap.set(cls, (schoolMap.get(cls) || 0) + 1)
          })
          const schoolArr = Array.from(schoolMap.entries()).map(([className, count]) => ({
            className, count
          }))
          schoolArr.sort((a,b) => b.count - a.count)
          
          // 保存全校排名（并列排名：相同违纪次数的班级排名相同）
          let currentRank = 1
          let previousCount = null
          schoolArr.forEach((item, index) => {
            if (previousCount !== null && item.count < previousCount) {
              // 违纪次数变化了，更新排名为当前索引+1
              currentRank = index + 1
            }
            allSchoolRankMap.set(item.className, currentRank)
            previousCount = item.count
          })
          
        //   console.log('全校排名已计算:', allSchoolRankMap)
        } catch (e) {
          console.error('获取全校排名失败,将使用本地排名:', e)
        }
        
        // 步骤2: 获取自己有权限的数据(用于显示)
        let allList = []
        // 分页获取当前用户可见的违纪记录
        try {
          let pageNo2 = 1
          const pageSize2 = 100
          let hasMore2 = true
          while (hasMore2) {
            const params2 = { pageNo: pageNo2, pageSize: pageSize2, classDate }
            const response2 = await uni.request({
              url: config.baseUrl + '/admin-api/ao/patrol/page',
              method: 'GET',
              header: {
                'Authorization': 'Bearer ' + token,
                'tenant-id': '1',
                'Content-Type': 'application/json'
              },
              data: params2
            })
            const [err2, res2] = response2
            if (!err2 && res2.data && res2.data.code === 0) {
              const list2 = res2.data.data?.list || []
              allList = allList.concat(list2)
              const total2 = res2.data.data?.total || 0
              if (allList.length >= total2) {
                hasMore2 = false
              } else {
                pageNo2++
              }
            } else {
              hasMore2 = false
              if (pageNo2 === 1) {
                uni.showToast({ title: '查询失败：' + (res2?.data?.msg || '未知错误'), icon: 'none', duration: 3000 })
              }
            }
          }
        } catch (errAllList) {
          // console.error('获取可见违纪列表失败:', errAllList)
        }
        // 根据当前 rankingType 分支：class 或 teacher
        if (this.rankingType === 'class') {
          // 统计班级违纪次数并显示（保留原有逻辑）
          this.totalRecords = allList.length
          const map = new Map()
          allList.forEach(item => {
            const cls = item.className || '未知班级'
            map.set(cls, (map.get(cls) || 0) + 1)
          })
          
          // 转换为数组,添加全校排名信息
          const arr = Array.from(map.entries()).map(([className, count]) => {
            const displayName = this.removeLeadingZeros(className)
            const rank = allSchoolRankMap.get(className) || 0  // 获取全校排名
            return { 
              className,
              displayName,
              count,
              rank  // 全校排名
            }
          })
          
          // 按全校排名排序(如果有),否则按违纪次数排序
          arr.sort((a,b) => {
            if (a.rank && b.rank) {
              return a.rank - b.rank  // 按全校排名升序
            }
            return b.count - a.count  // 按违纪次数降序
          })
          
          this.topList = arr
          // 维持 targetRank 行为（不过现在没有班级搜索框）
        } else {
          // 教师排名：需要统计当前账号所关联的教师在上课时的违纪次数
          await this.loadTeacherRanking(allList, allSchoolList)
        }
        this.loaded = true
      } catch (e) {
        uni.showToast({ title: '查询异常：' + e.message, icon: 'none', duration: 3000 })
      } finally {
        this.loading = false
      }
    },
    formatDate(d) {
      const y = d.getFullYear()
      const m = String(d.getMonth()+1).padStart(2,'0')
      const day = String(d.getDate()).padStart(2,'0')
      return `${y}-${m}-${day}`
    },

    // 统计当前登录用户作为授课老师时的违纪记录
    async loadTeacherRanking(allList, allSchoolList) {
      // allSchoolList: 全校所有违纪记录（未过滤权限）
      
      const token = getToken()
      if (!token) {
        this.teacherEmptyMessage = '未登录，无法查看数据'
        this.teacherList = []
        return
      }
      
      // 获取当前用户信息
      let currentTeacherName = ''
      
      try {
        const userInfoResponse = await uni.request({
          url: config.baseUrl + '/admin-api/system/user/profile/get',
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + token,
            'tenant-id': '1'
          }
        })
        
        const [err, res] = userInfoResponse
        if (!err && res.data && res.data.code === 0) {
          currentTeacherName = res.data.data?.remark || res.data.data?.nickname || ''
        }
      } catch (e) {
        console.error('获取用户信息失败:', e)
      }
      
      // === 计算全校老师排名 ===
      // 1. 统计所有老师的违纪次数
      const teacherCountMap = new Map()
      allSchoolList.forEach(item => {
        const teacherName = item.teacherName || '未知老师'
        if (teacherName && teacherName !== '未知老师') {
          teacherCountMap.set(teacherName, (teacherCountMap.get(teacherName) || 0) + 1)
        }
      })
      
      if (teacherCountMap.size === 0) {
        this.teacherEmptyMessage = '该时间范围内暂无违纪记录'
        this.teacherList = []
        return
      }
      
      // 2. 转为数组并按违纪次数降序排序
      const allTeachersArray = Array.from(teacherCountMap.entries()).map(([name, count]) => ({
        teacherName: name,
        count: count,
        isCurrentUser: name === currentTeacherName
      }))
      allTeachersArray.sort((a, b) => b.count - a.count)
      
      // 3. 计算并列排名
      let currentRank = 1
      let previousCount = -1
      
      allTeachersArray.forEach((teacher, index) => {
        if (teacher.count !== previousCount) {
          currentRank = index + 1  // 违纪次数改变时，排名=索引+1
          previousCount = teacher.count
        }
        teacher.rank = currentRank
      })
      
      // 4. 根据角色决定显示内容
      if (this.isPatrolTeacher) {
        // 巡班老师：显示全校所有老师排名
        this.teacherList = allTeachersArray
      } else {
        // 普通老师：只显示自己的记录
        if (!currentTeacherName) {
          this.teacherEmptyMessage = '未找到老师信息，请联系管理员配置账号'
          this.teacherList = []
          return
        }
        
        const myRecords = allSchoolList.filter(item => item.teacherName === currentTeacherName)
        const totalCount = myRecords.length
        
        if (totalCount === 0) {
          this.teacherEmptyMessage = '该时间范围内暂无违纪记录'
          this.teacherList = []
          this.teacherClassList = []
          this.teacherSummary = ''
          this.totalTeacherClasses = 0
          this.myTeacherRank = null
          this.totalTeachers = 0
          return
        }
        
        // 获取当前老师的排名
        const currentTeacher = allTeachersArray.find(t => t.teacherName === currentTeacherName)
        this.myTeacherRank = currentTeacher ? currentTeacher.rank : null
        this.totalTeachers = allTeachersArray.length
        
        // 按班级分组统计（当前老师的班级）
        const classMap = new Map()
        myRecords.forEach(item => {
          const className = item.className || '未知班级'
          classMap.set(className, (classMap.get(className) || 0) + 1)
        })
        
        // 转为数组并排序（按违纪次数降序）
        const classList = Array.from(classMap.entries()).map(([className, count]) => ({
          originalClassName: className,
          displayName: this.removeLeadingZeros(className),
          count
        }))
        classList.sort((a, b) => b.count - a.count)
        
        // 设置显示数据
        this.teacherClassList = classList
        this.totalTeacherClasses = classList.length
        this.teacherSummary = `我上课时违纪总次数: ${totalCount} 次`
        this.teacherList = [{ placeholder: true }]  // 用于控制显示
      }
    },
    removeLeadingZeros(className) {
      // 去掉班级名称中数字前面的0
      // 1. 去除开头的0: "0高技2404班" -> "高技2404班"
      // 2. 去除数字中的前导0: "0210" -> "210", "2404班" 保持不变
      let result = className.replace(/^0+([^0])/g, '$1')  // 去除开头的0
      result = result.replace(/(\D)0+(\d)/g, '$1$2')  // 去除非数字后的0
      return result
    },
    
    goToClassDetail(className) {
      // 跳转到班级违纪详情页面，传递班级名称和时间范围
      const today = new Date()
      let startDate = ''
      let endDate = ''
      
      if (this.rangeIndex === 0) {
        // 本周
        const day = today.getDay() || 7
        const monday = new Date(today)
        monday.setDate(today.getDate() - (day-1))
        const sunday = new Date(monday)
        sunday.setDate(monday.getDate() + 6)
        startDate = this.formatDate(monday)
        endDate = this.formatDate(sunday)
      } else if (this.rangeIndex === 1) {
        // 本月
        const start = new Date(today.getFullYear(), today.getMonth(), 1)
        const end = new Date(today.getFullYear(), today.getMonth()+1, 0)
        startDate = this.formatDate(start)
        endDate = this.formatDate(end)
      } else {
        // 学期
        const start = new Date(today.getFullYear(), 0, 1)
        startDate = this.formatDate(start)
        endDate = this.formatDate(today)
      }
      
      uni.navigateTo({
        url: `/pages/patrol/class-violation-detail?className=${encodeURIComponent(className)}&startDate=${startDate}&endDate=${endDate}`
      })
    }
  }
}
</script>

<style scoped>
.ranking-container { padding: 15px; background: #f5f5f5; min-height: 100vh }
.ranking-card { background: #fff; border-radius: 12px; padding: 16px }

/* 顶部切换 + 时间选择（同一行等高） */
.tab-row {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  align-items: stretch;
}
.tab-btn {
  flex: 1;
  height: 44px;
  padding: 0 12px;
  background: #f3f3f3;
  color: #666;
  border-radius: 8px;
  font-size: 14px;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  transition: all 0.3s;
}
.tab-btn.active {
  background: #5DADE2;
  color: #fff;
  font-weight: bold;
}
.picker-flex { flex: 1; }
/* picker 内部视图复用按钮样式，确保等高居中 */
.picker-btn {}

.result { margin-top: 12px }
.summary { padding: 12px; background: #f9f9f9; border-radius: 8px; margin-bottom: 12px }
.summary text { display: block; font-size: 13px; color: #666; margin: 4px 0 }
.rank-info { padding: 16px; background: #e3f2fd; border-radius: 8px; margin-bottom: 12px; text-align: center; cursor: pointer }
.rank-info text { display: block; font-size: 15px; color: #333; font-weight: 500 }
.no-data { padding: 20px; text-align: center; color: #999 }
.top-list { margin-top: 10px; border-top: 1px solid #f0f0f0; padding-top: 10px }
.top-item { 
  padding: 10px 0; 
  border-bottom: 1px solid #f0f0f0; 
  font-size: 14px; 
  cursor: pointer;
}
.top-item:active { background: #f5f5f5 }
.loading { text-align: center; padding: 20px; color: #999 }
</style>